package top.xiaoshuaila.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import top.xiaoshuaila.config.security.JwtTokenUtil;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketController implements WebSocketMessageBrokerConfigurer {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        /*
        * 1.将/ws/ep路径注册为stomp的端点,用户连接了这个端点就可以进行websocket通讯,支持socketjs
        * 2.setAllowedOrigins("*")设置允许跨域
        * 3.withSockJS()设置支持socketJs访问*/
        registry.addEndpoint("/ws/ep")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                //先判断是不是连接
                StompHeaderAccessor accessor =
                        MessageHeaderAccessor.getAccessor(message,
                        StompHeaderAccessor.class);
                //如果是连接,则进行jwt验证后将security权限共享
                if(StompCommand.CONNECT.equals(accessor.getCommand()))
                {
                    String token =
                            accessor.getFirstNativeHeader("Auth" +
                                    "-Token");
                    if(!"".equals(token)){
                        String authToken=token.substring(tokenHead.length());
                        String username =
                                jwtTokenUtil.getUserNameFromToken(authToken);
                        if(!"".equals(username)){
                            UserDetails userDetails =
                                    userDetailsService.loadUserByUsername(username);
                            if(jwtTokenUtil.validateToken(authToken,userDetails)){
                                UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //配置代理域,可以配置多个,配置代理目的前缀为/queue,可以在配置域上想客户端推送消息
        registry.enableSimpleBroker("/queue");
    }
}
